USE [QLDL]
GO

/****** Object:  StoredProcedure [dbo].[sp_ThemPhieuThuTien]    Script Date: 01/08/2011 23:26:36 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [dbo].[sp_ThemPhieuThuTien]
	@MaDaiLy nvarchar(10), @SoTienThu money, @NgayThu date
as
begin
	declare @TienNo money
	declare @NgayTiepNhan date
	select @TienNo = TienNo, @NgayTiepNhan = NgayTiepNhan from DAILY where MaDaiLy = @MaDaiLy
	if (@SoTienThu = 0)
		return 1
	if(@SoTienThu > @TienNo)
		return 2
	if (@NgayThu < @NgayTiepNhan)
		return 3
	
	declare @MaPTT nvarchar(10)
	select @MaPTT = MaPTT from PHIEUTHUTIEN order by (CAST(RIGHT(MaPTT, LEN(MaPTT) - 3) as int)) asc
	if (@MaPTT is not null)
		set @MaPTT = N'PTT' + CAST((CAST(RIGHT(@MaPTT, LEN(@MaPTT) - 3) as int) + 1) as nvarchar)
	else
		set @MaPTT = N'PTT1'
		
	insert into PHIEUTHUTIEN values(@MaPTT, @MaDaiLy, @SoTienThu, @NgayThu)
	update DAILY set TienNo = TienNo - @SoTienThu where MaDaiLy = @MaDaiLy
	return 0
end

GO


